<template>
  <div>
    <el-row :gutter="20" class="toolbar">
      <el-col :span="6">
        <el-select
            v-model="selectedStock"
            placeholder="支持模糊搜索"
            style="width: 250px"
            filterable
            remote
            clearable
            reserve-keyword
            :remote-method="searchStocks"
            :loading="stockLoading"
            @change="onStockChange"
        >
          <el-option
              v-for="item in stockOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-col>

      <el-col :span="5">
        <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="开始时间"
            :picker-options="startPickerOptions"
        ></el-date-picker>
      </el-col>

      <el-col :span="5">
        <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="结束时间"
            :picker-options="endPickerOptions"
        ></el-date-picker>
      </el-col>

      <el-col :span="4">
        <el-button type="primary" @click="fetchRiskData">查询</el-button>
      </el-col>
    </el-row>

    <div ref="chartRef" style="width: 100%; height: 500px; margin-top: 20px;"></div>

    <el-row class="risk-summary" style="margin-top: 20px;" type="flex" justify="space-around">
      <el-col>第1天预测: {{ yesterdayPrice }}</el-col>
      <el-col>第2天预测: {{ todayPrice }}</el-col>
      <el-col>第3天预测: {{ tomorrowPrice }}</el-col>
      <el-col>预测精度: {{ accuracy }}</el-col>
    </el-row>

    <!-- 相关新闻区域 -->
    <div class="news-section" style="margin-top: 30px;">
      <el-card>
        <div slot="header" class="clearfix">
          <span style="font-weight: bold; font-size: 16px;">📰 相关新闻</span>
          <el-button 
            style="float: right; padding: 3px 10px" 
            type="text" 
            @click="fetchStockNews"
            :loading="newsLoading"
          >
            刷新
          </el-button>
        </div>
        
        <div v-if="newsLoading" style="text-align: center; padding: 40px;">
          <i class="el-icon-loading" style="font-size: 24px;"></i>
          <p style="margin-top: 10px;">加载新闻中...</p>
        </div>
        
        <div v-else-if="newsList.length === 0" style="text-align: center; padding: 40px; color: #909399;">
          <i class="el-icon-document" style="font-size: 48px;"></i>
          <p style="margin-top: 10px;">暂无新闻数据</p>
        </div>
        
        <el-timeline v-else>
          <el-timeline-item 
            v-for="(news, index) in displayedNews" 
            :key="index"
            :timestamp="news['发布时间'] || news.pub_time" 
            placement="top"
          >
            <el-card shadow="hover">
              <h4 style="margin: 0 0 10px 0;">
                <a :href="news['新闻链接'] || news.url" target="_blank" style="color: #303133; text-decoration: none;">
                  {{ news['新闻标题'] || news.title }}
                </a>
              </h4>
              <p style="color: #606266; font-size: 14px; line-height: 1.6; margin: 10px 0;">
                {{ news['新闻内容'] || news.content }}
              </p>
              <div style="margin-top: 10px; font-size: 12px; color: #909399;">
                <span>📅 {{ news['发布时间'] || news.pub_time }}</span>
                <span style="margin-left: 15px;">📰 来源: {{ news['文章来源'] || news.source || '-' }}</span>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        
        <div v-if="newsList.length > newsDisplayLimit" style="text-align: center; margin-top: 20px;">
          <el-button 
            type="primary" 
            plain 
            @click="loadMoreNews"
            v-if="newsDisplayLimit < newsList.length"
          >
            加载更多 ({{ newsList.length - newsDisplayLimit }} 条)
          </el-button>
          <el-button 
            type="text" 
            @click="newsDisplayLimit = 10"
            v-else
          >
            收起
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import http from '../utils/request';
import * as echarts from 'echarts';

export default {
  name: 'StockRiskPage_Autoformer',
  data() {
    const today = new Date();
    const oneYearAgo = new Date(today);
    oneYearAgo.setFullYear(today.getFullYear() - 1);

    return {
      selectedStock: '',
      stockSymbol: '',
      stockOptions: [],
      stockLoading: false,

      startDate: null,
      endDate: null,
      yesterdayPrice: '-',
      todayPrice: '-',
      tomorrowPrice: '-',
      accuracy: '-',
      chartInstance: null,
      today,
      oneYearAgo,
      
      // 新闻相关
      newsList: [],
      newsLoading: false,
      newsDisplayLimit: 10,
      startPickerOptions: {
        disabledDate: (time) => {
          return time < this.oneYearAgo || time > this.today;
        }
      },
      endPickerOptions: {
        disabledDate: (time) => {
          const maxFuture = new Date(this.today);
          maxFuture.setDate(maxFuture.getDate() + 21);
          return time < this.startDate || time > maxFuture;
        }
      }
    };
  },
  computed: {
    displayedNews() {
      return this.newsList.slice(0, this.newsDisplayLimit);
    }
  },
  mounted() {
    this.chartInstance = echarts.init(this.$refs.chartRef);
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
  },
  methods: {
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    // 模糊搜索股票
    async searchStocks(query) {
      this.stockLoading = true;

      const params = query
          ? { query }
          : { page: 1, page_size: 500 }; // 空输入显示全部

      try {
        const response = await http.get('/api/stock_base/', { params });
        const data = response.data.results || [];
        this.stockOptions = data.map(item => ({
          value: item.symbol,
          label: item.symbol + ' ' + item.name
        }));
      } catch (err) {
        console.error(err);
        this.$message.error('股票搜索失败');
      } finally {
        this.stockLoading = false;
      }
    },

    onStockChange(value) {
      this.stockSymbol = value;
      // 当选择股票时,自动加载新闻
      if (value) {
        this.fetchStockNews();
      }
    },

    // 获取股票新闻
    async fetchStockNews() {
      if (!this.stockSymbol) {
        this.$message.warning('请先选择股票');
        return;
      }
      
      this.newsLoading = true;
      this.newsList = [];
      
      try {
        // 从股票代码中提取纯数字部分 (sh600519 -> 600519)
        const stockCode = this.stockSymbol.replace(/[a-zA-Z]/g, '');
        
        console.log('准备获取新闻, 股票代码:', stockCode);
        console.log('完整请求URL:', '/api/stock_news/?stock_code=' + stockCode);
        
        const response = await http.get('/api/stock_news/', {
          params: { 
            stock_code: stockCode,
            limit: 100
          }
        });
        
        console.log('=== 新闻接口响应 ===');
        console.log('完整响应:', response);
        console.log('响应数据:', response.data);
        console.log('响应类型:', typeof response.data);
        console.log('是否为数组:', Array.isArray(response.data));
        
        if (response.data) {
          // 检查多种可能的数据结构
          if (response.data.news && Array.isArray(response.data.news)) {
            console.log('找到 news 字段, 数量:', response.data.news.length);
            this.newsList = response.data.news;
          } else if (response.data.data && Array.isArray(response.data.data)) {
            console.log('找到 data 字段, 数量:', response.data.data.length);
            this.newsList = response.data.data;
          } else if (Array.isArray(response.data)) {
            console.log('直接是数组, 数量:', response.data.length);
            this.newsList = response.data;
          } else {
            console.log('未知的数据格式:', Object.keys(response.data));
            console.log('第一层数据:', response.data);
            this.$message.warning('数据格式不匹配,请查看控制台');
          }
          
          if (this.newsList.length > 0) {
            console.log('第一条新闻示例:', this.newsList[0]);
            this.$message.success(`加载了 ${this.newsList.length} 条新闻`);
          } else {
            console.warn('新闻列表为空');
            this.$message.warning('未获取到新闻数据');
          }
        } else {
          console.error('response.data 为空');
          this.$message.warning('响应数据为空');
        }
      } catch (err) {
        console.error('=== 获取新闻失败 ===');
        console.error('错误对象:', err);
        console.error('错误响应:', err.response);
        console.error('错误信息:', err.message);
        this.$message.error('获取新闻失败: ' + (err.response?.data?.message || err.message));
      } finally {
        this.newsLoading = false;
      }
    },

    // 加载更多新闻
    loadMoreNews() {
      this.newsDisplayLimit += 10;
    },

    fetchRiskData() {
      if (!this.stockSymbol) {
        this.$message.warning('请选择股票');
        return;
      }
      if (!this.startDate || !this.endDate) {
        this.$message.warning('请选择开始和结束时间');
        return;
      }

      http.post('/api/predict/', {
        stock_code: this.stockSymbol,
        model_name: 'Autoformer'
      })
          .then(res => {
            console.log('后端返回的完整数据:', res);
            console.log('res.data:', res.data);
            
            const predictions = res.data.predictions || [];
            
            console.log('预测数据条数:', predictions.length);
            
            if (predictions.length > 0) {
              console.log('预测数据第一条的所有字段:', Object.keys(predictions[0]));
              console.log('预测数据第一条完整内容:', predictions[0]);
            }
            
            if (predictions.length === 0) {
              this.$message.warning('未获取到预测数据,请检查股票代码');
              return;
            }
            
            // 提取预测数据
            const dates = predictions.map(d => d.date);
            const openPrices = predictions.map(d => d.open);
            const closePrices = predictions.map(d => d.close);
            const highPrices = predictions.map(d => d.high);
            const lowPrices = predictions.map(d => d.low);
            const volumes = predictions.map(d => d.volume);
            
            console.log('日期示例:', dates.slice(0, 3));
            console.log('收盘价示例:', closePrices.slice(0, 3));
            
            // 准备K线图数据 [open, close, low, high]
            const candlestickData = predictions.map(d => [d.open, d.close, d.low, d.high]);
            
            // 更新统计信息 (预测数据)
            if (closePrices.length >= 3) {
              this.yesterdayPrice = '¥' + Number(closePrices[0]).toFixed(2);
              this.todayPrice = '¥' + Number(closePrices[1]).toFixed(2);
              this.tomorrowPrice = '¥' + Number(closePrices[2]).toFixed(2);
            } else if (closePrices.length >= 1) {
              this.yesterdayPrice = '-';
              this.todayPrice = '¥' + Number(closePrices[0]).toFixed(2);
              this.tomorrowPrice = closePrices.length > 1 ? '¥' + Number(closePrices[1]).toFixed(2) : '-';
            }
            
            // 计算预测精度(如果后端返回)
            this.accuracy = res.data.accuracy ? Number(res.data.accuracy).toFixed(2) + '%' : '-';

            // 计算成交量的缩放比例
            const maxVolume = Math.max(...volumes);
            const volumeData = volumes.map((vol, idx) => ({
              value: vol,
              itemStyle: {
                color: closePrices[idx] >= openPrices[idx] ? '#ef5350' : '#26a69a'
              }
            }));

            // 绘制图表
            this.chartInstance.setOption({
              title: { 
                text: '基于Autoformer模型的股票价格预测',
                left: 'center',
                textStyle: {
                  fontSize: 18,
                  fontWeight: 'bold'
                }
              },
              tooltip: { 
                trigger: 'axis',
                axisPointer: {
                  type: 'cross',
                  crossStyle: {
                    color: '#999'
                  }
                },
                formatter: function(params) {
                  if (!params || params.length === 0) return '';
                  
                  const dataIndex = params[0].dataIndex;
                  const date = dates[dataIndex];
                  const open = openPrices[dataIndex];
                  const close = closePrices[dataIndex];
                  const high = highPrices[dataIndex];
                  const low = lowPrices[dataIndex];
                  const volume = volumes[dataIndex];
                  
                  // 日期格式化
                  const dateStr = date.length === 8 
                    ? date.substring(0, 4) + '-' + date.substring(4, 6) + '-' + date.substring(6, 8)
                    : date;
                  
                  const change = close - open;
                  const changePercent = ((change / open) * 100).toFixed(2);
                  const changeColor = change >= 0 ? '#ef5350' : '#26a69a';
                  
                  return `
                    <div style="padding: 8px;">
                      <div style="font-weight: bold; margin-bottom: 8px;">${dateStr}</div>
                      <div>开盘: ¥${Number(open).toFixed(2)}</div>
                      <div>收盘: ¥${Number(close).toFixed(2)}</div>
                      <div>最高: ¥${Number(high).toFixed(2)}</div>
                      <div>最低: ¥${Number(low).toFixed(2)}</div>
                      <div style="color: ${changeColor}">
                        涨跌: ${change >= 0 ? '+' : ''}¥${change.toFixed(2)} (${change >= 0 ? '+' : ''}${changePercent}%)
                      </div>
                      <div>成交量: ${(volume / 10000).toFixed(2)}万</div>
                    </div>
                  `;
                }
              },
              legend: {
                data: ['K线', '成交量'],
                top: '30px'
              },
              grid: [
                {
                  left: '10%',
                  right: '10%',
                  top: '70px',
                  height: '50%'
                },
                {
                  left: '10%',
                  right: '10%',
                  top: '68%',
                  height: '18%'
                }
              ],
              xAxis: [
                {
                  type: 'category',
                  data: dates,
                  boundaryGap: true,
                  axisLine: { lineStyle: { color: '#8392A5' } },
                  axisLabel: {
                    formatter: function(value) {
                      if (value && value.length === 8) {
                        return value.substring(4, 6) + '-' + value.substring(6, 8);
                      }
                      return value;
                    }
                  },
                  splitLine: { show: false },
                  gridIndex: 0
                },
                {
                  type: 'category',
                  data: dates,
                  gridIndex: 1,
                  axisLabel: { show: false },
                  axisLine: { lineStyle: { color: '#8392A5' } },
                  splitLine: { show: false }
                }
              ],
              yAxis: [
                {
                  scale: true,
                  name: '价格(¥)',
                  splitLine: { 
                    show: true,
                    lineStyle: {
                      color: '#E0E6F1',
                      type: 'dashed'
                    }
                  },
                  axisLabel: {
                    formatter: '¥{value}'
                  },
                  gridIndex: 0
                },
                {
                  scale: true,
                  name: '成交量',
                  splitLine: { show: false },
                  axisLabel: {
                    formatter: function(value) {
                      return (value / 10000).toFixed(0) + '万';
                    }
                  },
                  gridIndex: 1
                }
              ],
              dataZoom: [
                {
                  type: 'inside',
                  xAxisIndex: [0, 1],
                  start: 0,
                  end: 100
                },
                {
                  show: true,
                  xAxisIndex: [0, 1],
                  type: 'slider',
                  bottom: '5%',
                  start: 0,
                  end: 100,
                  height: 20
                }
              ],
              series: [
                {
                  name: 'K线',
                  type: 'candlestick',
                  data: candlestickData,
                  itemStyle: {
                    color: '#ef5350',        // 阳线颜色(涨)
                    color0: '#26a69a',       // 阴线颜色(跌)
                    borderColor: '#ef5350',  // 阳线边框
                    borderColor0: '#26a69a'  // 阴线边框
                  },
                  xAxisIndex: 0,
                  yAxisIndex: 0
                },
                {
                  name: '成交量',
                  type: 'bar',
                  data: volumeData,
                  xAxisIndex: 1,
                  yAxisIndex: 1,
                  barWidth: '60%'
                }
              ]
            });
          })
          .catch(err => {
            console.error('请求失败详情:', err);
            console.error('错误响应:', err.response);
            if (err.response) {
              this.$message.error(`获取股票数据失败: ${err.response.status} - ${err.response.data?.message || err.response.statusText}`);
            } else if (err.request) {
              this.$message.error('网络请求失败,请检查网络连接');
            } else {
              this.$message.error('获取股票数据失败: ' + err.message);
            }
          });
    }
  }
};
</script>

<style scoped>
.toolbar {
  margin-bottom: 10px;
}
.risk-summary {
  font-size: 16px;
  font-weight: bold;
}
</style>


